import { useEffect, useState } from "react";
import {
  Card,
  List,
  Typography,
  Pagination,
  Input,
  Space,
  Button,
  AutoComplete,
  Modal,
  Form,
  InputNumber,
  Select,
  message,
  Checkbox,
  Popconfirm,
  Alert,
  Tag,
} from "antd";
import { useTheme } from "../contexts/ThemeContext";
import {
  SearchOutlined,
  HistoryOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import "antd/dist/reset.css";
import {
  fetchUsers,
  createUser,
  updateUser,
  deleteUser,
  batchDeleteUsers,
  updateUserStatus,
  forceLogout,
} from "../api/users";
import { uploadImage } from "../api/upload";
import { isAdmin } from "../utils/auth";

export default function Users() {
  const { isDarkMode } = useTheme();

  // 权限检查：只有admin用户才能访问用户管理
  if (!isAdmin()) {
    return (
      <div style={{ maxWidth: 1200, margin: "20px auto", padding: "0 16px" }}>
        <Card style={{ textAlign: "center", padding: "60px 20px" }}>
          <Typography.Title level={3} type="danger">
            权限不足
          </Typography.Title>
          <Typography.Text type="secondary" style={{ fontSize: 16 }}>
            抱歉，您没有权限访问用户管理功能。只有管理员用户才能访问此页面。
          </Typography.Text>
        </Card>
      </div>
    );
  }

  const [users, setUsers] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [loading, setLoading] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const [username, setUsername] = useState("");
  const [searchHistory, setSearchHistory] = useState([]);
  // 头像上传相关
  const [avatarUploading, setAvatarUploading] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState(null);
  // 新增/编辑模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [userForm] = Form.useForm();
  // 批量删除状态
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  // 存储搜索历史的key
  const SEARCH_HISTORY_KEY = "users_search_history";
  // 当前用户ID
  const currentUserId = localStorage.getItem("userId");

  // 处理头像上传
  const handleAvatarChange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    setAvatarUploading(true);
    try {
      const res = await uploadImage(file);
      if (
        (res.code === 1 || res.code === 200) &&
        res.data &&
        res.data.oss_url
      ) {
        setAvatarUrl(res.data.oss_url);
        userForm.setFieldsValue({ img: res.data.oss_url });
        message.success("头像上传成功");
      } else {
        message.error(res.msg || "图片上传失败");
      }
    } catch (err) {
      message.error(err.message || "上传失败");
    } finally {
      setAvatarUploading(false);
    }
  };

  useEffect(() => {
    if (isModalVisible && editingUser && editingUser.img) {
      setAvatarUrl(editingUser.img);
    } else if (!isModalVisible) {
      setAvatarUrl(null);
    }
  }, [isModalVisible, editingUser]);

  // 初始化时加载搜索历史
  useEffect(() => {
    const savedHistory = localStorage.getItem(SEARCH_HISTORY_KEY);
    if (savedHistory) {
      try {
        setSearchHistory(JSON.parse(savedHistory));
      } catch (e) {
        setSearchHistory([]);
      }
    }
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      const params = { page, size: pageSize };
      if (username) {
        params.username = username;
      }
      try {
        const res = await fetchUsers(params);
        // 兼容老数据结构
        let userList = [];
        if (Array.isArray(res)) {
          userList = res;
          setTotal(res.length);
        } else {
          userList = res.list || [];
          setTotal(res.total || 0);
        }

        // 用户列表已包含登录状态信息，直接使用
        setUsers(userList);
      } catch (error) {
        console.error("获取用户列表失败:", error);
        message.error(error.message || "获取用户列表失败");
        setUsers([]);
        setTotal(0);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [page, pageSize, username]);

  // 搜索处理函数
  const handleSearch = () => {
    const trimmedValue = searchValue.trim();
    if (trimmedValue) {
      // 保存搜索历史
      saveSearchHistory(trimmedValue);
    }
    setUsername(trimmedValue);
    setPage(1); // 搜索时重置到第一页
  };

  // 重置搜索
  const handleReset = () => {
    setSearchValue("");
    setUsername("");
    setPage(1);
  };

  // 处理回车键搜索
  const handleKeyPress = (e) => {
    if (e.key === "Enter") {
      handleSearch();
    }
  };

  // 保存搜索历史
  const saveSearchHistory = (searchTerm) => {
    if (!searchTerm) return;

    let newHistory = [...searchHistory];

    // 如果已存在，先移除
    newHistory = newHistory.filter((item) => item !== searchTerm);

    // 添加到开头
    newHistory.unshift(searchTerm);

    // 最多保存10条历史记录
    newHistory = newHistory.slice(0, 10);

    setSearchHistory(newHistory);
    localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(newHistory));
  };

  // 清空搜索历史
  const clearSearchHistory = () => {
    setSearchHistory([]);
    localStorage.removeItem(SEARCH_HISTORY_KEY);
  };

  // 生成搜索建议选项
  const getSearchOptions = () => {
    return searchHistory.map((item, index) => ({
      value: item,
      label: (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
          }}>
          <span>
            <HistoryOutlined style={{ marginRight: 8, color: "#999" }} />
            {item}
          </span>
        </div>
      ),
    }));
  };

  // 刷新用户列表数据
  const refreshUsers = async () => {
    setLoading(true);
    const params = { page, size: pageSize };
    if (username) {
      params.username = username;
    }

    try {
      const res = await fetchUsers(params);

      // 兼容老数据结构
      let userList = [];
      if (Array.isArray(res)) {
        userList = res;
        setTotal(res.length);
      } else {
        userList = res.list || [];
        setTotal(res.total || 0);
      }

      // 用户列表已包含登录状态信息，直接使用
      setUsers(userList);
    } catch (error) {
      console.error("获取用户列表失败:", error);
      message.error(error.message || "获取用户列表失败");
      setUsers([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 打开新增/编辑模态框
  const handleOpenModal = (user = null) => {
    setEditingUser(user);
    setIsModalVisible(true);
    if (user) {
      userForm.setFieldsValue({
        name: user.name,
        email: user.email,
        age: user.age,
        role: user.role || "user",
        password: user.password || "", // 编辑时回显密码（但隐藏显示）
        img: user.img || null, // 设置头像字段
      });
    } else {
      userForm.resetFields();
      userForm.setFieldsValue({
        role: "user",
      });
    }
  };

  // 关闭模态框
  const handleCloseModal = () => {
    setIsModalVisible(false);
    setEditingUser(null);
    userForm.resetFields();
  };

  // 保存用户
  const handleSaveUser = async (values) => {
    try {
      const userData = {
        name: values.name,
        email: values.email,
        age: values.age,
        role: values.role,
        img: values.img || avatarUrl || null, // 获取头像字段
      };

      // 如果是编辑用户且密码不为空，或者是新增用户，则包含密码
      if (
        !editingUser ||
        (editingUser && values.password && values.password.trim())
      ) {
        userData.password = values.password;
      }

      if (editingUser) {
        // 编辑
        await updateUser({
          ...userData,
          id: editingUser.id,
        });
        message.success("用户更新成功");
      } else {
        // 新增
        await createUser(userData);
        message.success("用户创建成功");
      }

      handleCloseModal();
      // 延迟刷新数据，等待ES同步
      setTimeout(() => {
        refreshUsers();
      }, 0);
    } catch (error) {
      console.error("保存用户失败:", error);
      message.error(error.message || "保存用户失败，请重试");
    }
  };

  // 删除单个用户
  const handleDeleteUser = async (id) => {
    try {
      await deleteUser(id);
      message.success("用户删除成功");
      // 延迟刷新数据，等待ES同步
      setTimeout(() => {
        refreshUsers();
      }, 0);
    } catch (error) {
      console.error("删除用户失败:", error);
      message.error(error.message || "删除用户失败，请重试");
    }
  };

  // 批量删除用户
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请先选择要删除的用户");
      return;
    }

    // 过滤掉当前用户
    const idsToDelete = selectedRowKeys.filter(
      (id) => String(id) !== String(currentUserId)
    );

    if (idsToDelete.length === 0) {
      message.error("不能删除当前登录用户");
      return;
    }

    if (idsToDelete.length < selectedRowKeys.length) {
      message.warning("已排除当前登录用户，无法删除");
    }

    try {
      await batchDeleteUsers(idsToDelete.join(","));
      message.success(`成功删除 ${idsToDelete.length} 个用户`);
      setSelectedRowKeys([]);
      // 延迟刷新数据，等待ES同步
      setTimeout(() => {
        refreshUsers();
      }, 0);
    } catch (error) {
      console.error("批量删除失败:", error);
      message.error(error.message || "批量删除失败，请重试");
    }
  };

  // 处理批量选择
  const handleSelectChange = (userId, checked) => {
    if (checked) {
      setSelectedRowKeys([...selectedRowKeys, userId]);
    } else {
      setSelectedRowKeys(selectedRowKeys.filter((id) => id !== userId));
    }
  };

  // 切换用户状态
  const handleToggleStatus = async (userId, currentStatus) => {
    try {
      const newStatus = currentStatus === 1 ? 0 : 1;
      await updateUserStatus(userId, newStatus);
      message.success(
        `用户状态已更新为${newStatus === 1 ? "已登录" : "未登录"}`
      );
      refreshUsers();
    } catch (error) {
      console.error("更新用户状态失败:", error);
      message.error(error.message || "更新用户状态失败，请重试");
    }
  };

  // 强制用户下线
  const handleForceLogout = async (userId) => {
    try {
      await forceLogout(userId);
      message.success("已强制用户下线");
      // 等待一下后重新获取用户信息
      setTimeout(() => {
        refreshUsers();
      }, 500);
    } catch (error) {
      console.error("强制下线失败:", error);
      message.error(error.message || "强制下线失败，请重试");
    }
  };

  // 全选/取消全选
  const handleSelectAll = (checked) => {
    if (checked) {
      // 全选时排除当前用户
      setSelectedRowKeys(
        users
          .filter((user) => String(user.id) !== String(currentUserId))
          .map((user) => user.id)
      );
    } else {
      setSelectedRowKeys([]);
    }
  };

  return (
    <div style={{ maxWidth: 1200, margin: "20px auto", padding: "0 16px" }}>
      {/* 页面标题 */}
      <div style={{ textAlign: "center", marginBottom: 32 }}>
        <Typography.Title
          level={2}
          style={{ color: "#1890ff", marginBottom: 8 }}>
          <UserOutlined /> 用户管理
        </Typography.Title>
        <Typography.Text type="secondary" style={{ fontSize: 16 }}>
          基于 Spring Boot 服务的用户管理与权限控制
        </Typography.Text>
      </div>

      <Card
        title={
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}>
            <span>用户列表</span>
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handleOpenModal()}>
                新增用户
              </Button>
              <Button
                icon={<ReloadOutlined />}
                onClick={refreshUsers}
                loading={loading}
                title="刷新用户列表">
                刷新
              </Button>
              {users.length > 0 && (
                <Checkbox
                  checked={
                    selectedRowKeys.length > 0 &&
                    selectedRowKeys.length === users.length
                  }
                  indeterminate={
                    selectedRowKeys.length > 0 &&
                    selectedRowKeys.length < users.length
                  }
                  onChange={(e) => handleSelectAll(e.target.checked)}>
                  全选
                </Checkbox>
              )}
              {selectedRowKeys.length > 0 && (
                <Popconfirm
                  title="确定要删除选中的用户吗？"
                  onConfirm={handleBatchDelete}
                  okText="确定"
                  cancelText="取消">
                  <Button type="primary" danger icon={<DeleteOutlined />}>
                    删除选中 ({selectedRowKeys.length})
                  </Button>
                </Popconfirm>
              )}
            </Space>
          </div>
        }
        style={{
          maxWidth: 700,
          margin: "20px auto",
          borderRadius: 12,
          boxShadow: isDarkMode
            ? "0 2px 12px rgba(0,0,0,0.3)"
            : "0 2px 12px #eee",
          backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
          borderColor: isDarkMode ? "#434343" : "#d9d9d9",
          transition: "all 0.3s ease",
        }}>
        {/* 搜索框 */}
        <Space.Compact style={{ width: "100%", marginBottom: 16 }}>
          <AutoComplete
            style={{ flex: 1 }}
            options={getSearchOptions()}
            value={searchValue}
            onChange={setSearchValue}
            onSelect={(value) => setSearchValue(value)}
            onKeyPress={handleKeyPress}
            filterOption={false}
            dropdownRender={(menu) => (
              <div>
                {menu}
                {searchHistory.length > 0 && (
                  <div
                    style={{ padding: "8px", borderTop: "1px solid #f0f0f0" }}>
                    <Button
                      type="text"
                      size="small"
                      onClick={clearSearchHistory}
                      style={{ color: "#999" }}>
                      清空历史记录
                    </Button>
                  </div>
                )}
              </div>
            )}>
            <Input prefix={<SearchOutlined />} placeholder="请输入用户名搜索" />
          </AutoComplete>
          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
          <Button onClick={handleReset}>重置</Button>
        </Space.Compact>

        {/* 批量选择提示 */}
        {selectedRowKeys.length > 0 && (
          <Alert
            message={`已选择 ${selectedRowKeys.length} 条用户`}
            type="info"
            showIcon
            closable
            onClose={() => setSelectedRowKeys([])}
            style={{ marginBottom: 16 }}
          />
        )}

        <List
          itemLayout="horizontal"
          dataSource={users}
          loading={loading}
          renderItem={(user) => {
            console.log(
              `渲染用户 ${user.name}, 登录状态: ${user.loginStatus}, 设备数: ${user.onlineDeviceCount}`
            );
            const isCurrentUser = String(user.id) === String(currentUserId);
            return (
              <List.Item
                actions={[
                  ...(user.loginStatus === 1 && !isCurrentUser
                    ? [
                        <Popconfirm
                          key="logout"
                          title="确定要强制该用户下线吗？"
                          onConfirm={() => handleForceLogout(user.id)}
                          okText="是"
                          cancelText="否">
                          <Button
                            type="link"
                            danger
                            icon={<CloseCircleOutlined />}>
                            强制下线
                          </Button>
                        </Popconfirm>,
                      ]
                    : []),
                  <Button
                    key="edit"
                    type="link"
                    icon={<EditOutlined />}
                    onClick={() => handleOpenModal(user)}>
                    编辑
                  </Button>,
                  <Popconfirm
                    key="delete"
                    title="确定要删除这个用户吗？"
                    onConfirm={() => handleDeleteUser(user.id)}
                    okText="是"
                    cancelText="否"
                    disabled={isCurrentUser}>
                    <Button
                      type="link"
                      danger
                      icon={<DeleteOutlined />}
                      disabled={isCurrentUser}>
                      删除
                    </Button>
                  </Popconfirm>,
                ]}>
                <List.Item.Meta
                  avatar={
                    !isCurrentUser && (
                      <Checkbox
                        checked={selectedRowKeys.includes(user.id)}
                        onChange={(e) =>
                          handleSelectChange(user.id, e.target.checked)
                        }
                      />
                    )
                  }
                  title={
                    <div
                      style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <Typography.Text strong>
                        {user.name}
                        {isCurrentUser && (
                          <Tag color="cyan" style={{ marginLeft: 8 }}>
                            当前用户
                          </Tag>
                        )}
                      </Typography.Text>
                      <Tag color={user.loginStatus === 1 ? "green" : "red"}>
                        {user.loginStatus === 1 ? "已登录" : "未登录"}
                      </Tag>
                      {user.loginStatus === 1 && (
                        <Tag color="blue">
                          🔌 {user.onlineDeviceCount} 台设备
                        </Tag>
                      )}
                    </div>
                  }
                  description={
                    <>
                      <div>邮箱：{user.email}</div>
                      <div>年龄：{user.age}</div>
                      <div>
                        角色：{user.role === "admin" ? "管理员" : "用户"}
                      </div>
                    </>
                  }
                />
              </List.Item>
            );
          }}
        />

        <div style={{ textAlign: "center", marginTop: 24 }}>
          <Pagination
            current={page}
            pageSize={pageSize}
            total={total}
            showSizeChanger
            pageSizeOptions={["5", "10", "20", "50"]}
            onChange={(p, s) => {
              setPage(p);
              setPageSize(s);
            }}
            showTotal={(t) => `共 ${t} 条`}
          />
        </div>

        {/* 新增/编辑用户模态框 */}
        <Modal
          title={editingUser ? "编辑用户" : "新增用户"}
          open={isModalVisible}
          onCancel={handleCloseModal}
          footer={null}
          width={600}>
          <Form
            form={userForm}
            layout="vertical"
            onFinish={handleSaveUser}
            initialValues={{
              role: "user",
            }}>
            <Form.Item label="头像" name="img">
              <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
                <div style={{ position: "relative", display: "inline-block" }}>
                  <img
                    src={
                      avatarUrl || userForm.getFieldValue("img") || undefined
                    }
                    alt="头像"
                    style={{
                      width: 48,
                      height: 48,
                      borderRadius: "50%",
                      objectFit: "cover",
                      background: "#f0f0f0",
                    }}
                  />
                  <input
                    type="file"
                    accept="image/*"
                    style={{
                      position: "absolute",
                      left: 0,
                      top: 0,
                      width: "100%",
                      height: "100%",
                      opacity: 0,
                      cursor: "pointer",
                    }}
                    title="点击上传头像"
                    onChange={handleAvatarChange}
                    disabled={avatarUploading}
                  />
                  {avatarUploading && (
                    <div
                      style={{
                        position: "absolute",
                        left: 0,
                        top: 0,
                        width: "100%",
                        height: "100%",
                        background: "rgba(255,255,255,0.7)",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        borderRadius: "50%",
                      }}>
                      上传中...
                    </div>
                  )}
                </div>
              </div>
            </Form.Item>
            <Form.Item
              label="用户名"
              name="name"
              rules={[
                { required: true, message: "请输入用户名" },
                { min: 2, message: "用户名至少2个字符" },
                { max: 50, message: "用户名最多50个字符" },
              ]}>
              <Input placeholder="请输入用户名" />
            </Form.Item>

            <Form.Item
              label="邮箱"
              name="email"
              rules={[
                { required: true, message: "请输入邮箱" },
                { type: "email", message: "请输入有效的邮箱地址" },
              ]}>
              <Input placeholder="请输入邮箱" />
            </Form.Item>

            <Form.Item
              label="年龄"
              name="age"
              rules={[
                { required: true, message: "请输入年龄" },
                {
                  type: "number",
                  min: 1,
                  max: 120,
                  message: "请输入有效的年龄",
                },
              ]}>
              <InputNumber
                style={{ width: "100%" }}
                placeholder="请输入年龄"
                min={1}
                max={120}
              />
            </Form.Item>

            <Form.Item
              label="密码"
              name="password"
              rules={[
                ...(editingUser
                  ? [{ min: 6, message: "密码至少6个字符" }]
                  : [
                      { required: true, message: "请输入密码" },
                      { min: 6, message: "密码至少6个字符" },
                    ]),
              ]}>
              <Input.Password
                placeholder={
                  editingUser ? "修改密码（留空则不修改）" : "请输入密码"
                }
                autoComplete="new-password"
              />
            </Form.Item>

            <Form.Item
              label="角色"
              name="role"
              rules={[{ required: true, message: "请选择角色" }]}>
              <Select placeholder="请选择角色">
                <Select.Option value="user">用户</Select.Option>
                <Select.Option value="admin">管理员</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item style={{ marginBottom: 0, textAlign: "right" }}>
              <Space>
                <Button onClick={handleCloseModal}>取消</Button>
                <Button type="primary" htmlType="submit">
                  {editingUser ? "更新" : "创建"}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
}
